package com.nd.android.u.ui.activity.message_chat;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.nd.android.u.controller.factory.MessageFactory;
import com.nd.android.u.controller.innerInterface.IChatListItem;
import com.nd.android.u.controller.innerInterface.IMessageDisplay;
import com.nd.android.u.ui.beanStarApp.DisplayMessage_Person;
import com.nd.android.u.ui.widge.ChatListItemView;

/**
 * 聊天界面listview数据适配器
 * <br>Created 2014-8-28 下午7:27:58
 * @version  
 * @author   cb		
 * @see 	 
 */
public class MessageAdapter extends BaseAdapter{
	protected List<IMessageDisplay> list;
	protected Context mContext;
	/**
	 * 是否需要更新
	 */
	private boolean mIsNotify=false;
	/**
	 * @return the mIsNotify
	 */
	public boolean isIsNotify() {
		return mIsNotify;
	}

	/**
	 * @param mIsNotify the mIsNotify to set
	 */
	public void setIsNotify(boolean isNotify) {
		this.mIsNotify = isNotify;
	}


	/**
	 * MessageAdapter.构造方法
	 * <br>Created 2014-8-28 下午7:28:19
	 * @param context 环境变量
	 */
	public MessageAdapter(Context context) {
		this.mContext = context;
		list = new ArrayList<IMessageDisplay>();
	}
	
	
	@Override
	public int getCount() {
		if (list == null){
			return 0;
		}
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		if (list == null||position<0 || position >= getCount()){
			return null;
		}
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		IMessageDisplay message=list.get(position);
		IChatListItem view=null;
		if (convertView==null){
			//找不到可复用的view
			if (message.isChild()){
				view=new ChatListItemView(mContext);
			}else{
				view=MessageFactory.INSTANCE.getMessageView(mContext, message,false);
			}
		}else{
			if (message.isChild()){
				if (convertView instanceof ChatListItemView){
					view =(ChatListItemView) convertView;
				}else{
					view=new ChatListItemView(mContext);
				}
			}else{
				view = MessageFactory.INSTANCE.getMessageView(mContext, message,false);
			}
		}
		View returnView=(View) view;
		if (mIsNotify && message != null
				&& message instanceof DisplayMessage_Person) {
			returnView.setTag(true);
		}
		if(position==getCount()-1){
			mIsNotify=false;
		}
		view.setData(message);
		return returnView;
	}
	
	/**
	 * 设置数据源
	 * <br>Created 2014-8-28 下午7:28:56
	 * @param list 数据源
	 * @author  cb
	*/
	public void setList(List<IMessageDisplay> data) {
		if (data == null) {
			return;
		}
		
		this.list.clear();
		this.list.addAll(data);
		notifyDataSetChanged();
	}
}